// 页面内容管理
const pageContents = {
    home: `<div class="container">
        <div class="translation-card">
            <div class="language-selector">
                <div class="row w-100">
                    <div class="col-5">
                        <select class="form-select" id="sourceLanguage">
                            <option value="zh">中文</option>
                            <option value="en">英语</option>
                            <option value="ja">日语</option>
                            <option value="ko">韩语</option>
                            <option value="fr">法语</option>
                        </select>
                    </div>
                    <div class="col-2 text-center">
                        <button class="btn btn-link" id="switchLanguage">
                            <i class="fas fa-exchange-alt"></i>
                        </button>
                    </div>
                    <div class="col-5">
                        <select class="form-select" id="targetLanguage">
                            <option value="en">英语</option>
                            <option value="zh">中文</option>
                            <option value="ja">日语</option>
                            <option value="ko">韩语</option>
                            <option value="fr">法语</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="translation-input">
                <textarea class="form-control border-0" id="sourceText" rows="4" 
                          placeholder="请输入要翻译的文本"></textarea>
            </div>

            <div class="d-flex justify-content-between mb-3">
                <button class="btn btn-outline-primary action-button" id="clearText">
                    <i class="fas fa-times"></i> 清空
                </button>
                <button class="btn btn-primary action-button translate-button">
                    <i class="fas fa-language"></i> 翻译
                </button>
            </div>

            <div class="translation-result bg-light p-3 rounded" style="display: none;">
                <div class="result-text mb-3"></div>
                <div class="d-flex justify-content-between">
                    <button class="btn btn-outline-secondary btn-sm" id="copyResult">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" id="playAudio">
                        <i class="fas fa-volume-up"></i> 播放
                    </button>
                </div>
            </div>
        </div>

        <!-- 语音设置面板 -->
        <div class="card mt-3">
            <div class="card-header">
                语音设置
            </div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">语音音色</label>
                    <select class="form-select" id="voiceType">
                        <option value="female1">女声1</option>
                        <option value="female2">女声2</option>
                        <option value="male1">男声1</option>
                        <option value="male2">男声2</option>
                    </select>
                </div>
                <div class="mb-3">
                    <label class="form-label">语速调节</label>
                    <input type="range" class="form-range" id="speechRate" min="0.5" max="2" step="0.1" value="1">
                </div>
            </div>
        </div>
    </div>`,

    voice: `<div class="container">
        <div class="translation-card">
            <div class="language-selector mb-4">
                <div class="row w-100">
                    <div class="col-5">
                        <select class="form-select" id="sourceLanguage">
                            <option value="zh">中文</option>
                            <option value="en">英语</option>
                            <option value="ja">日语</option>
                            <option value="ko">韩语</option>
                            <option value="fr">法语</option>
                        </select>
                    </div>
                    <div class="col-2 text-center">
                        <button class="btn btn-link" id="switchLanguage">
                            <i class="fas fa-exchange-alt"></i>
                        </button>
                    </div>
                    <div class="col-5">
                        <select class="form-select" id="targetLanguage">
                            <option value="en">英语</option>
                            <option value="zh">中文</option>
                            <option value="ja">日语</option>
                            <option value="ko">韩语</option>
                            <option value="fr">法语</option>
                        </select>
                    </div>
                </div>
            </div>

            <div class="voice-input-area text-center mb-4">
                <div class="voice-status mb-3">
                    <i class="fas fa-microphone fa-3x"></i>
                    <p class="mt-2" id="voiceStatus">点击麦克风开始录音</p>
                </div>
                <button class="btn btn-lg btn-primary rounded-circle p-4" id="recordButton">
                    <i class="fas fa-microphone"></i>
                </button>
            </div>

            <div class="recognition-result mb-4">
                <div class="card">
                    <div class="card-header">语音识别结果</div>
                    <div class="card-body">
                        <p id="recognitionText" class="mb-0">等待语音输入...</p>
                    </div>
                </div>
            </div>

            <div class="translation-result bg-light p-3 rounded mb-4" style="display: none;">
                <h6 class="mb-3">翻译结果</h6>
                <div class="result-text mb-3"></div>
                <div class="d-flex justify-content-between">
                    <button class="btn btn-outline-secondary btn-sm" id="copyResult">
                        <i class="fas fa-copy"></i> 复制
                    </button>
                    <button class="btn btn-outline-secondary btn-sm" id="playAudio">
                        <i class="fas fa-volume-up"></i> 播放
                    </button>
                </div>
            </div>
        </div>
    </div>`,

    video: `<div class="container">
        <div class="row">
            <div class="col-12">
                <div class="video-container position-relative mb-3">
                    <video id="remoteVideo" class="w-100" autoplay playsinline></video>
                    <video id="localVideo" class="position-absolute" style="width: 100px; right: 10px; bottom: 10px;" 
                           autoplay playsinline muted></video>
                </div>
                <div class="video-controls d-flex justify-content-center gap-3 mb-3">
                    <button class="btn btn-outline-primary rounded-circle" id="toggleVideo">
                        <i class="fas fa-video"></i>
                    </button>
                    <button class="btn btn-outline-primary rounded-circle" id="toggleAudio">
                        <i class="fas fa-microphone"></i>
                    </button>
                    <button class="btn btn-danger rounded-circle" id="endCall">
                        <i class="fas fa-phone-slash"></i>
                    </button>
                </div>
            </div>
        </div>
    </div>`,

    settings: `<div class="container">
        <div class="card mb-4">
            <div class="card-header">蓝牙设置</div>
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-center mb-3">
                    <div>
                        <h6 class="mb-0">蓝牙状态</h6>
                        <div class="bluetooth-status bluetooth-disconnected">
                            <i class="fas fa-bluetooth-b me-2"></i>
                            <span>蓝牙未连接</span>
                        </div>
                    </div>
                    <button class="btn btn-primary" id="connectBluetooth">连接设备</button>
                </div>
                <div id="deviceList" class="list-group"></div>
            </div>
        </div>

        <div class="card mb-4">
            <div class="card-header">账号信息</div>
            <div class="card-body">
                <div class="mb-3">
                    <label class="form-label">用户名</label>
                    <input type="text" class="form-control" value="测试用户" readonly>
                </div>
                <div class="mb-3">
                    <label class="form-label">会员状态</label>
                    <input type="text" class="form-control" value="免费版" readonly>
                </div>
                <button class="btn btn-danger w-100" id="logout">退出登录</button>
            </div>
        </div>
    </div>`,

    login: `<div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6">
                <div class="card mt-5">
                    <div class="card-header text-center">
                        <h4>用户登录/注册</h4>
                    </div>
                    <div class="card-body">
                        <form id="loginForm">
                            <div class="mb-3">
                                <label for="username" class="form-label">用户名</label>
                                <input type="text" class="form-control" id="username" required>
                            </div>
                            <div class="mb-3">
                                <label for="password" class="form-label">密码</label>
                                <input type="password" class="form-control" id="password" required>
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary">登录/注册</button>
                            </div>
                        </form>
                        <div class="mt-3 text-center">
                            <small class="text-muted">首次登录将自动创建账号</small>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>`
};

// 页面路由管理
const routes = {
    home: './pages/home.html',
    voice: './pages/voice.html',
    video: './pages/video.html',
    settings: './pages/settings.html',
    login: './pages/login.html'
};

// 加载页面内容
function loadPage(page) {
    const pageContent = document.getElementById('pageContent');
    if (!pageContent) return;

    // 更新导航栏激活状态
    document.querySelectorAll('.nav-link').forEach(link => {
        if (link.getAttribute('href') === `#${page}`) {
            link.classList.add('active');
        } else {
            link.classList.remove('active');
        }
    });

    // 如果页面内容已经在pageContents中定义，直接使用
    if (pageContents[page]) {
        pageContent.innerHTML = pageContents[page];
        initializePageFeatures(page);
        return;
    }

    // 否则尝试从文件加载
    fetch(routes[page])
        .then(response => response.text())
        .then(html => {
            pageContent.innerHTML = html;
            initializePageFeatures(page);
        })
        .catch(error => {
            console.error('页面加载错误:', error);
            pageContent.innerHTML = '<div class="alert alert-danger">页面加载失败</div>';
        });
}

// 蓝牙状态管理
let isBluetoothConnected = false;

// 修改API基础URL配置
const API_BASE_URL = 'http://localhost:8000/api/v1';

// 修改登录函数
async function login(username, password) {
    try {
        console.log('尝试登录:', username);
        
        // 使用管理员登录端点
        const formData = new URLSearchParams();
        formData.append('username', username);
        formData.append('password', password);

        const response = await fetch(`${API_BASE_URL}/admin/login`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
                'Accept': 'application/json'
            },
            body: formData
        });

        console.log('登录/注册响应状态:', response.status);
        
        const data = await response.json();
        console.log('登录/注册响应数据:', data);

        if (response.ok) {
            // 保存认证信息
            localStorage.setItem('access_token', data.access_token);
            localStorage.setItem('username', username);
            localStorage.setItem('is_logged_in', 'true');
            return true;
        } else {
            throw new Error(data.detail || '登录失败');
        }
    } catch (error) {
        console.error('登录/注册错误:', error);
        if (error.message === 'Failed to fetch') {
            throw new Error('无法连接到服务器，请检查后端服务是否启动（http://localhost:8000）');
        }
        throw error;
    }
}

// 检查登录状态
function checkLoginStatus() {
    return localStorage.getItem('is_logged_in') === 'true';
}

// 登出函数
function logout() {
    localStorage.removeItem('user_info');
    localStorage.removeItem('is_logged_in');
    loadPage('login');
}

// 修改登录页面初始化函数
function initializeLogin() {
    const loginForm = document.getElementById('loginForm');

    if (loginForm) {
        loginForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;

            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }

            try {
                await login(username, password);
                alert('登录成功');
                loadPage('home');
            } catch (error) {
                console.error('登录处理错误:', error);
                alert('登录/注册失败: ' + error.message);
            }
        });
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    // 检查登录状态
    if (!checkLoginStatus() && window.location.hash !== '#login') {
        loadPage('login');
        return;
    }

    // 注册路由事件
    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();
            const page = this.getAttribute('href').substring(1);
            
            // 如果未登录且不是登录页面，重定向到登录页面
            if (!checkLoginStatus() && page !== 'login') {
                loadPage('login');
                return;
            }
            
            loadPage(page);
        });
    });

    // 加载初始页面
    const page = window.location.hash.substring(1) || 'home';
    if (checkLoginStatus() || page === 'login') {
        loadPage(page);
    } else {
        loadPage('login');
    }
});

// 初始化蓝牙功能
async function initializeBluetooth() {
    try {
        if (!navigator.bluetooth) {
            throw new Error('您的浏览器不支持蓝牙功能');
        }
        
        // 不在页面加载时自动请求蓝牙权限
        updateBluetoothStatus();
    } catch (error) {
        console.error('蓝牙初始化失败:', error);
        updateBluetoothStatus();
    }
}

// 请求蓝牙设备连接
async function requestBluetoothDevice() {
    try {
        const device = await navigator.bluetooth.requestDevice({
            acceptAllDevices: true
        });
        isBluetoothConnected = true;
        updateBluetoothStatus();
        return device;
    } catch (error) {
        console.error('蓝牙连接失败:', error);
        isBluetoothConnected = false;
        updateBluetoothStatus();
        throw error;
    }
}

// 更新蓝牙状态显示
function updateBluetoothStatus() {
    const statusElements = document.querySelectorAll('.bluetooth-status');
    statusElements.forEach(element => {
        element.className = `bluetooth-status ${isBluetoothConnected ? 'bluetooth-connected' : 'bluetooth-disconnected'}`;
        element.textContent = isBluetoothConnected ? '蓝牙已连接' : '蓝牙未连接';
    });
}

// 初始化页面特定功能
function initializePageFeatures(page) {
    switch (page) {
        case 'home':
            initializeTranslation();
            break;
        case 'voice':
            initializeVoiceTranslation();
            break;
        case 'video':
            initializeVideoChat();
            break;
        case 'settings':
            initializeSettings();
            break;
        case 'login':
            initializeLogin();
            break;
    }
}

// 添加认证相关的辅助函数
function getAuthHeaders() {
    const token = localStorage.getItem('access_token');
    return {
        'Authorization': `Bearer ${token}`,
        'Content-Type': 'application/json'
    };
}

function checkAuth() {
    const token = localStorage.getItem('access_token');
    if (!token) {
        loadPage('login');
        return false;
    }
    return true;
}

// 修改翻译功能初始化
function initializeTranslation() {
    if (!checkAuth()) return;

    const translateButton = document.querySelector('.translate-button');
    if (translateButton) {
        translateButton.addEventListener('click', async () => {
            const sourceText = document.getElementById('sourceText').value;
            const sourceLang = document.getElementById('sourceLanguage').value;
            const targetLang = document.getElementById('targetLanguage').value;

            if (!sourceText) {
                alert('请输入要翻译的文本');
                return;
            }

            try {
                const response = await fetch('http://localhost:8000/api/v1/ai/translate/text', {
                    method: 'POST',
                    headers: getAuthHeaders(),
                    body: JSON.stringify({
                        text: sourceText,
                        source_lang: sourceLang,
                        target_lang: targetLang
                    })
                });

                if (!response.ok) {
                    throw new Error('翻译请求失败');
                }

                const data = await response.json();
                const resultDiv = document.querySelector('.translation-result');
                resultDiv.style.display = 'block';
                resultDiv.querySelector('.result-text').textContent = data.translated_text;
            } catch (error) {
                console.error('翻译错误:', error);
                alert('翻译失败: ' + error.message);
            }
        });
    }
}

// 修改语音翻译功能初始化
function initializeVoiceTranslation() {
    if (!checkAuth()) return;

    const recordButton = document.getElementById('recordButton');
    if (recordButton) {
        let mediaRecorder;
        let audioChunks = [];

        recordButton.addEventListener('click', async () => {
            try {
                if (!mediaRecorder || mediaRecorder.state === 'inactive') {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    mediaRecorder = new MediaRecorder(stream);
                    audioChunks = [];

                    mediaRecorder.addEventListener('dataavailable', event => {
                        audioChunks.push(event.data);
                    });

                    mediaRecorder.addEventListener('stop', async () => {
                        const audioBlob = new Blob(audioChunks);
                        const formData = new FormData();
                        formData.append('file', audioBlob);
                        formData.append('target_lang', document.getElementById('targetLanguage').value);

                        try {
                            const response = await fetch('http://localhost:8000/api/v1/ai/speech-to-text', {
                                method: 'POST',
                                headers: {
                                    'Authorization': getAuthHeaders().Authorization
                                },
                                body: formData
                            });

                            if (!response.ok) {
                                throw new Error('语音识别请求失败');
                            }

                            const data = await response.json();
                            document.getElementById('recognitionText').textContent = data.original_text;
                            
                            const resultDiv = document.querySelector('.translation-result');
                            resultDiv.style.display = 'block';
                            resultDiv.querySelector('.result-text').textContent = data.translated_text;
                        } catch (error) {
                            console.error('语音识别错误:', error);
                            alert('语音识别失败: ' + error.message);
                        }
                    });

                    mediaRecorder.start();
                    recordButton.innerHTML = '<i class="fas fa-stop"></i>';
                    document.getElementById('voiceStatus').textContent = '正在录音...';
                } else {
                    mediaRecorder.stop();
                    recordButton.innerHTML = '<i class="fas fa-microphone"></i>';
                    document.getElementById('voiceStatus').textContent = '点击麦克风开始录音';
                }
            } catch (error) {
                console.error('录音错误:', error);
                alert('无法访问麦克风: ' + error.message);
            }
        });
    }
}

// 修改设置页面初始化
function initializeSettings() {
    if (!checkAuth()) return;

    const logoutButton = document.getElementById('logout');
    if (logoutButton) {
        logoutButton.addEventListener('click', () => {
            localStorage.removeItem('access_token');
            loadPage('login');
        });
    }

    const connectBluetoothBtn = document.getElementById('connectBluetooth');
    if (connectBluetoothBtn) {
        connectBluetoothBtn.addEventListener('click', async () => {
            try {
                await requestBluetoothDevice();
            } catch (error) {
                alert('无法连接蓝牙设备，请确保设备已开启并在范围内');
            }
        });
    }
}

// 悬浮窗管理
class FloatingWindow {
    static show(content) {
        let floatingWindow = document.querySelector('.floating-window');
        if (!floatingWindow) {
            floatingWindow = document.createElement('div');
            floatingWindow.className = 'floating-window';
            document.body.appendChild(floatingWindow);
        }
        floatingWindow.innerHTML = content;
    }

    static hide() {
        const floatingWindow = document.querySelector('.floating-window');
        if (floatingWindow) {
            floatingWindow.remove();
        }
    }
}

// 读取
const otherLangIndex = uni.getStorageSync('otherLangIndex');
const myLangIndex = uni.getStorageSync('myLangIndex');
const micIndex = uni.getStorageSync('micIndex');
const voiceIndex = uni.getStorageSync('voiceIndex');

// 保存
uni.setStorageSync('otherLangIndex', 1);
uni.setStorageSync('myLangIndex', 2);
uni.setStorageSync('micIndex', 0);
uni.setStorageSync('voiceIndex', 1);

function onPickerChange(key, e) {
    const idx = e.detail.value;
    if (key === 'otherLang') {
        otherLangIndex = idx;
        uni.setStorageSync('otherLangIndex', idx);
    }
    if (key === 'myLang') {
        myLangIndex = idx;
        uni.setStorageSync('myLangIndex', idx);
    }
    if (key === 'mic') {
        micIndex = idx;
        uni.setStorageSync('micIndex', idx);
    }
    if (key === 'voice') {
        voiceIndex = idx;
        uni.setStorageSync('voiceIndex', idx);
    }
}

// main.js
Vue.prototype.$getGlobalSetting = (key) => uni.getStorageSync(key);
Vue.prototype.$setGlobalSetting = (key, value) => uni.setStorageSync(key, value); 